﻿using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using Lost;

/// <summary>
/// Photo manager.
/// </summary>
public class PhotoManager : MonoBehaviour {
	public static PhotoManager _instance;
	string PhotoesDirectory = "Photoes/";
	///后缀
	const string suffix = ".png";
	public Texture2D CurPhoto{
		get{ return DataSaver.LoadTexture2D (photoes [curIndex]);}
	}
	[SerializeField] List<string> photoes = new List<string> ();
	public int Count{
		get{ return photoes.Count;}
	}
	[SerializeField] Camera photoCamera;
	[SerializeField] RawImage rawImg;
	[SerializeField] RawImage screenImg;
	RenderTexture cameraScreen;
	Sprite sprite;

	int CurIndex{
		get{ return curIndex;}
		set{ 
			if (photoes.Count <= 0) {
				return;
			}
			curIndex = value;
			if (curIndex < 0) {
				curIndex = 0;
			} else if (curIndex >= photoes.Count) {
				curIndex = photoes.Count - 1;
			}
			rawImg.texture = CurPhoto as Texture;
			print (curIndex);
		}
	}
	int curIndex = 0;

	//PhotoesDirectory = Application.dataPath + "/" + PhotoesDirectory;
	void Awake(){
		_instance = this;
	}
	void Start(){
		cameraScreen = new RenderTexture (128, 128, 0);
		photoCamera.targetTexture = cameraScreen;
		screenImg.texture = cameraScreen;
		LoadPhotoes ();
	}

	void LoadPhotoes(){
		if (!Directory.Exists (PhotoesDirectory)) {
			Directory.CreateDirectory (PhotoesDirectory);
		}
		string[] files = Directory.GetFiles (PhotoesDirectory);
		int len = files.Length;
		foreach (string f in files) {
			if (f.EndsWith (suffix)) {
				photoes.Add (f);
			}
		}
		CurIndex = 0;
	}

	void Update(){
		if (MyInput.GetInputOfType (InputType.TAKE_PHOTO)) {
			TakePhoto ();
		}
	}

	void TakePhoto(){
		string fileName = PhotoesDirectory + (photoes.Count).ToString () + suffix;
		DataSaver.SaveRenderTexture (cameraScreen, fileName);
		photoes.Add (fileName);
	}

	public void PrePhoto(){
		CurIndex--;
	}
	public void NextPhoto(){
		CurIndex++;
	}

}
